package cat.inkubator.plugin4j.download;

import cat.inkubator.plugin4j.xml.Plugin;
import java.util.Vector;

/**
 *
 * @author dlsarmen
 */
public class DownloadMonitor {

    private int actualDownloads = 0;
    private int maxDownloads = 3;

    synchronized public void download( Vector<Plugin> plugins, String targetFolder ){

        try{
            while( plugins.size() > 0 ){

                if( actualDownloads < maxDownloads ){
                    actualDownloads++;
                    Plugin plugin = plugins.firstElement();
                    plugins.removeElementAt(0);

                    Downloader download = new Downloader(plugin, this, targetFolder);
                    Thread t = new Thread(download);
                    t.start();
                }else{
                    this.wait();
                }

            }

            //TO WAIT IF URLS ARRAY IS EMPTY BEFORE ALL THE DOWNLOADS FINISH
            while( actualDownloads != 0 ) this.wait();
        }catch( java.lang.InterruptedException inter ){
            inter.printStackTrace();
        }

    }

    synchronized public void downloadFinish(){
        actualDownloads--;
        this.notifyAll();
    }

}
